package Java.com.wang.House;

import java.util.ArrayList;

public class WareHouse {
    ArrayList<Integer> products = null;
    private final int MAXN = 20;

    public WareHouse() {
        products = new ArrayList<>();
    }

    public void add(int number) {
        try {
            synchronized (products) {
                if (products.size() < MAXN) {
                    System.out.printf("生产者向消费者仓库中存入了一个编号为%d商品\n", number);
                    products.add(number);
                    System.out.printf("仓库中共有：" + products.size() + "个\n");
                    products.notify();
                } else if (products.size() == MAXN) {
                    System.out.println("仓库已满，请耐心等待消费者来取走商品！！！");
                    products.wait();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public void get(int number) {
        try {
            synchronized (products) {
                if (products.size() == 0) {
                    System.out.println("仓库已空，请耐心等待商品添加！！！");
                    products.wait();
                } else if (products.size() > 0) {
                    System.out.printf("消费者取出了编号为%d商品\n", products.get(0));
                    products.remove(0);
                    System.out.printf("仓库中共有：" + products.size() + "个\n");
                    products.notify();
                }
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

}
